clear all
set more 1
set maxvar 120000
set matsize 11000

use $scratch\data_WI_WII_nominations.dta, replace

gen obs = _n
local total_obs = _N
set obs `total_obs'
gen A = .

set output error
forvalues i = 1(1)`total_obs' {
set output proc
di "Generate A"
di "`i' of `total_obs'"
set output error
gen A`i' =.
}

set output error
forvalues i = 1(1)`total_obs' {
set output proc
di "Replace A with Friendship Links"
di "`i' of `total_obs'"
set output error

foreach j in MF1AID MF2AID MF3AID MF4AID MF5AID  FF1AID FF2AID FF3AID FF4AID FF5AID   {
su obs if AID == `j'[`i'] & `j'[`i']!=. , meanonly
if r(N) >0 {

replace A`i' = 1 in `r(min)'
*Symmetric;
replace A`r(min)' = 1 in `i'

}
}
}

save "$scratch_large/temp_friends.dta", replace
keep  idschool saturated AID class cogn1 cogn2 cogn3 cogn4 cogn5 ///
	  race  ///
	  A1* A2* A3* A4* A5* A6* A7* A8* A9* age
save "$scratch_large/temp_netanalysis.dta", replace
	  
	  
	  
use "$scratch_large/temp_friends.dta", clear
*******************************;
*Create Peer's Skills
*******************************;

forvalues j = 1(1)5{

gen mean_peer_cogn`j' =  .
gen n_peers_cogn`j' = .

forvalues i = 1(1)`total_obs' {


set output proc
di "Generate Mean Peers Skills (Cogn `j')"
di "`i' of `total_obs'"
set output error

sum cogn`j' if A`i' == 1 , meanonly

replace mean_peer_cogn`j' = r(mean) in `i'
replace n_peers_cogn`j' = r(N) in `i'


}
}

save $scratch\final_skills_peers_withAdj.dta, replace


************************************************************;
*Create Friend from the nominations in WII (peers t+1);
************************************************************;

use $scratch\final_skills_peers_withAdj.dta, clear
local total_obs = _N


rename AID id_child
drop A*
rename id_child AID


set output error
forvalues i = 1(1)`total_obs' {
set output proc
di "Generate A_WII"
di "`i' of `total_obs'"
set output error
gen A_wII_`i' =.
}

set output error
forvalues i = 1(1)`total_obs' {
set output proc
di "Replace A_WII with Friendship Links"
di "`i' of `total_obs'"
set output error

foreach j in MF_AID1 MF_AID2 MF_AID3 MF_AID4 MF_AID5 FF_AID1 FF_AID2 FF_AID3 FF_AID4 FF_AID5  {
su obs if AID == `j'[`i'] & `j'[`i']!=. , meanonly
if r(N) >0 {

replace A_wII_`i' = 1 in `r(min)'
*Symmetric;
replace A_wII_`r(min)' = 1 in `i'

}
}
}




*******************************;
*Create Peer's Skills (peers t+1)
*******************************;


forvalues j = 2(1)5{

gen mean_peer_cogn`j'_t2 =  .
gen n_peers_cogn`j'_t2 = .


forvalues i = 1(1)`total_obs' {


set output proc
di "Generate Mean Peers Skills in WII (Cogn `j' t+1)"
di "`i' of `total_obs'"
set output error

sum cogn`j'_t2 if A_wII_`i' == 1 , meanonly

replace mean_peer_cogn`j'_t2 = r(mean) in `i'
replace n_peers_cogn`j'_t2 = r(N) in `i'

}
}


drop A_wII*
save $scratch\final_skills_peers.dta, replace

   